import time
import threading
import sys
import json
import librosa
import soundfile as sf
import os



import nls


URL="wss://nls-gateway-cn-shanghai.aliyuncs.com/ws/v1"
TOKEN= '64ed4fe7b8024b90b2bd0a877a6332cd'  #"yourToken"  #参考https://help.aliyun.com/document_detail/450255.html获取token
APPKEY='RgY65M8PEqOJqaGs'   #"yourAppkey"    #获取Appkey请前往控制台：https://nls-portal.console.aliyun.com/applist

#以下代码会根据音频文件内容反复进行实时语音识别（文件转写）
class TestSt:
    def __init__(self, tid, test_file):
        self.__th = threading.Thread(target=self.__test_run)
        self.__id = tid
        self.__test_file = test_file
   
    def loadfile(self, filename):
        with open(filename, "rb") as f:
            self.__data = f.read()
    
    def start(self):
        self.loadfile(self.__test_file)
        self.__th.start()

    def test_on_sentence_begin(self, message, *args):
        print("test_on_sentence_begin:{}".format(message))

    def test_on_sentence_end(self, message, *args):
        print("test_on_sentence_end:{}".format(message))

        try:
            # 检查message是否是字符串并尝试解析
            if isinstance(message, str):
                message_dict = json.loads(message)  # 将字符串解析为字典
            else:
                message_dict = message  # 如果不是字符串，直接使用
 
 
            self.final_result = message_dict.get('payload', {}).get('result', '')

            filename = os.path.basename(self.__test_file)[:-4] + ".txt"
            directory = os.path.dirname(self.__test_file)
            print(directory + "/" + filename)

            # 追加模式，不会覆盖原有内容
            with open(directory+"/" + filename, 'a', encoding='utf-8') as file:
                 file.write(self.final_result + "\n")


            print(f"最终识别结果: {self.final_result}")
        except json.JSONDecodeError:
            print("Failed to decode message, check the format.")


    def test_on_start(self, message, *args):
        print("test_on_start:{}".format(message))

    def test_on_error(self, message, *args):
        print("on_error args=>{}".format(args))

    def test_on_close(self, *args):
        print("on_close: args=>{}".format(args))

    def test_on_result_chg(self, message, *args):
        print("test_on_chg:{}".format(message))

    def test_on_completed(self, message, *args):
        print("on_completed:args=>{} message=>{}".format(args, message))


    def __test_run(self):
        print("thread:{} start..".format(self.__id))
        sr = nls.NlsSpeechTranscriber(
                    url=URL,
                    token=TOKEN,
                    appkey=APPKEY,
                    on_sentence_begin=self.test_on_sentence_begin,
                    on_sentence_end=self.test_on_sentence_end,
                    on_start=self.test_on_start,
                    on_result_changed=self.test_on_result_chg,
                    on_completed=self.test_on_completed,
                    on_error=self.test_on_error,
                    on_close=self.test_on_close,
                    callback_args=[self.__id]
                )

        print("{}: session start".format(self.__id))
        r = sr.start(aformat="pcm",
        enable_intermediate_result=True,
        enable_punctuation_prediction=True,
        enable_inverse_text_normalization=True)

        self.__slices = zip(*(iter(self.__data),) * 640)
        for i in self.__slices:
            sr.send_audio(bytes(i))
            time.sleep(0.01)

        sr.ctrl(ex={"test":"tttt"})
        time.sleep(1)

        r = sr.stop()
        print("{}: sr stopped:{}".format(self.__id, r))
        time.sleep(1)


def singleruntest(inputWav):
    """单线程运行测试"""
    print(f"开始处理音频文件: {inputWav}")

    if not os.path.exists(inputWav):
        print(f"文件不存在: {inputWav}")
        return  0

    t = TestSt("single_thread", inputWav)
    t.start()
    t.join()  # 等待线程完成
    print("处理完成！")

    return 1


# inputWav = '/media/qy/sdb1/projects/test1/2speakers_example.wav'  # asr_example_hotword.wav'
def multiruntest(inputWav,num = 500):
    print("  inputWav =  ")
    print(inputWav)
    for i in range(0, num):
        name = "thread" + str(i)
        t = TestSt(name,  inputWav)
        t.start()


nls.enableTrace(False)

#inputWav = '/media/qy/sdb1/projects/test1/2speakers_example.wav'
#multiruntest(inputWav,1)



